<?php

class PermissionController extends BaseController {

    public function index() {

        $aData = array(
            'sPage_Title'       => trans('navigation.admin.permission'),
            'sPage_Description' => trans('navigation.admin-description.permission'),
            'Roles'             => Role::where('type', 'GROUP')->get(),
        );

        return View::make("permission.page", $aData);
    }

    public function postAjaxAssignList() {
        $aResponse = [];

        if (Request::get('sAction') && Request::get('sGroupActionName')) {

            $aResponse['sStatus'] = 'OK';

            switch (Request::get('sGroupActionName')) {
                case 'delete':
                    DB::table('assigned_roles')->whereIn('id', Request::get('id'))->delete();
                    $aResponse['sMessage'] = trans('validation.custom.success-title');
                    break;

                default:
                    break;
            }
        }

        // <editor-fold defaultstate="collapsed" desc="Filter Data">
        /* Individual column filtering */
        $aRoles = DB::table('assigned_roles')->whereIn('role_id', Role::where('type', 'GROUP')->lists('id'));

        $aColumns = array('user_id', 'username', 'rolename');
        foreach ($aColumns as $sColumnName) {
            if (Request::get('filter_' . $sColumnName)) {

                switch ($sColumnName) {
                    case 'user_id':
                        $aRoles->where($sColumnName, Request::get('filter_' . $sColumnName));
                        break;

                    case 'username':
                        $userids = User::where('username', 'like', '%' . Request::get('filter_' . $sColumnName) . '%')->lists('id');
                        $aRoles->whereIn('role_id', $userids ? $userids : [''] );
                        break;

                    case 'rolename':
                        $aRoles->where('role_id', Request::get('filter_' . $sColumnName));
                        break;

                    default:
                        break;
                }
            }
        }

        $iTotalRecords = $aRoles->count();

        /*
         * Paging
         */
        if (Request::get('iDisplayLength') != '-1') {
            $aRoles->skip(Request::get('iDisplayStart'))->take(Request::get('iDisplayLength'));
        }
        // </editor-fold>

        $aRoles = $aRoles->get();

        foreach ($aRoles as $key => $role) {
            $user = User::find($role->user_id);

            $aRoles[$key]->checkbox = '<input type="checkbox" name="id[]" value="' . $role->id . '">';
            $aRoles[$key]->user_id  = $role->user_id;
            $aRoles[$key]->username = $user->saint . ' - ' . $user->username;
            $aRoles[$key]->username = trim($aRoles[$key]->username, ' - ');
            $aRoles[$key]->rolename = Role::find($role->role_id)->name;
            $aRoles[$key]->actions  = '<a href="' . route('profile', ['id' => $role->id]) . '" class="btn btn-xs default btn-edit"><i class="fa fa-search"></i> ' . trans('system.button.view') . '</a>';
        }

        return $this->generateResponse($aResponse, $iTotalRecords, $aRoles);
    }

    private function generateResponse($aResponse = [], $iTotalRecords = 0, $aRoles = []) {

        $aResponse = $aResponse + array(
            "iTotalRecords"        => DB::table('assigned_roles')->count(),
            "iTotalDisplayRecords" => $iTotalRecords,
            "sEcho"                => Request::get('sEcho'),
            'aaData'               => $aRoles
        );

        return Response::json($aResponse);
    }

    public function getAjaxLoadPage($page) {
        $aChilData = [];
        switch ($page) {
            case 'role':
                $sLayout = 'table-role';
                $aData   = Role::where('type', 'GROUP')->get();
                break;

            case 'permission':
                $sLayout = 'table-permission';
                $aData   = Permission::orderBy('name')->get();
                break;

            case 'permission-role':
                $sLayout = 'table-permission-role';
                $aData   = Permission::orderBy('name')->get();
                break;

            default:
                $sLayout = 'table-permission';
                $aData   = [];
                break;
        }

        return View::make('permission.' . $sLayout, $aChilData + [
                'page'  => $page,
                'aData' => $aData,
        ]);
    }

    public function getAjaxCreatePage($page) {

        switch ($page) {
            case 'role':
                $sLayout = 'new-role';
                break;

            case 'permission':
                $sLayout = 'new-permission';
                break;

            default:
                $sLayout = 'new-role';
                break;
        }

        $aData = [
            'url' => route('permission-create', ['page' => $page]),
        ];

        return View::make('permission.' . $sLayout, $aData);
    }

    function postAjaxCreatePage($page) {

        $aResponse = array(
            'status'  => 200,
            'message' => trans('validation.custom.success-title'),
        );

        try {
            switch ($page) {
                case 'role':
                    $role          = new Role;
                    $role->type    = 'GROUP';
                    $role->name    = trim(Input::get('name'));
                    $role->updater = Auth::user()->id;
                    $role->save();
                    break;

                case 'permission':
                    $permission               = new Permission;
                    $permission->name         = trim(Input::get('name'));
                    $permission->display_name = trim(Input::get('display_name'));
                    $permission->updater      = Auth::user()->id;
                    $permission->save();
                    break;

                default:
                    break;
            }
        } catch (Exception $exc) {
            $aResponse = array(
                'status'  => 0,
                'message' => trans('validation.custom.error-title'),
            );
        }

        return Response::json($aResponse);
    }

    public function getAjaxEditPage($page, $id) {

        $aData = [];

        switch ($page) {
            case 'role':
                $sLayout = 'new-role';
                $Object  = Role::find($id);
                break;

            case 'permission':
                $sLayout = 'new-permission';
                $Object  = Permission::find($id);
                break;

            case 'permission-role':
                $sLayout = 'new-permission-role';
                $Object  = Permission::find($id);
                $aData   = [
                    'Roles'                 => Role::where('type', 'GROUP')->get(),
                    'permission_role_names' => $Object->roles()->get()->lists('name'),
                    'Users'                 => User::huynhtruong()->get(),
                ];
                break;

            default:
                $sLayout = 'new-role';
                break;
        }

        return View::make('permission.' . $sLayout, $aData + [
                'url'    => route('permission-edit', [
                    'page' => $page,
                    'id'   => $id,
                ]),
                'Object' => isset($Object) && $Object ? $Object : new stdClass()
        ]);
    }

    public function postAjaxEditPage($page, $id) {
        $aResponse = array(
            'status'  => 200,
            'message' => trans('validation.custom.success-title'),
        );

        try {
            switch ($page) {
                case 'role':
                    $role = Role::find($id);
                    if ($role) {
                        $role->name    = trim(Input::get('name'));
                        $role->updater = Auth::user()->id;
                        $role->save();
                    }
                    break;

                case 'permission':
                    $permission = Permission::find($id);
                    if ($permission) {
                        $permission->name         = trim(Input::get('name'));
                        $permission->display_name = trim(Input::get('display_name'));
                        $permission->updater      = Auth::user()->id;
                        $permission->save();
                    }
                    break;

                case 'permission-role':
                    $permission = Permission::find($id);

                    if ($permission) {
                        $permission_role_ids = $permission->roles()->get()->lists('id');

                        if (Input::get('role_group_id')) {
                            $role_attach = array_diff(Input::get('role_group_id'), $permission_role_ids);
                            if ($role_attach) {
                                $permission->roles()->attach($role_attach, ['updater' => Auth::user()->id]);
                            }

                            //Remove Old Data
                            $role_detach = array_diff($permission_role_ids, Input::get('role_group_id'));
                        } else {
                            //Remove Old Data
                            $role_detach = $permission_role_ids;
                        }

                        if ($role_detach) {
                            $role_detach = Role::whereIn('id', $role_detach)->where('type', 'GROUP')->lists('id');
                            if ($role_detach) {
                                $permission->roles()->detach($role_detach);
                                $role_detach = [];
                            }
                        }

                        if (Input::get('role_personal_id')) {

                            // <editor-fold defaultstate="collapsed" desc="Add New Personal Role">
                            $role_name          = Role::where('type', 'PERSONAL')->whereIn('name', Input::get('role_personal_id'))->lists('name');
                            $new_personal_roles = array_diff(Input::get('role_personal_id'), $role_name);

                            if ($new_personal_roles) {
                                foreach ($new_personal_roles as $userid) {
                                    $role          = new Role;
                                    $role->type    = 'PERSONAL';
                                    $role->name    = $userid;
                                    $role->updater = Auth::user()->id;
                                    $role->save();

                                    $role->users()->attach($userid);
                                }
                            }
                            // </editor-fold>

                            $role_id     = Role::where('type', 'PERSONAL')->whereIn('name', Input::get('role_personal_id'))->lists('id');
                            $role_attach = array_diff($role_id, $permission_role_ids);
                            if ($role_attach) {
                                $permission->roles()->attach($role_attach, ['updater' => Auth::user()->id]);
                            }

                            //Remove Old Data
                            $role_detach = array_diff($permission_role_ids, $role_id);
                        } else {
                            //Remove Old Data
                            $role_detach = $permission_role_ids;
                        }

                        if ($role_detach) {
                            $role_detach = Role::whereIn('id', $role_detach)->where('type', 'PERSONAL')->lists('id');
                            if ($role_detach) {
                                $permission->roles()->detach($role_detach);
                                $role_detach = [];
                            }
                        }
                    }

                    break;

                default:
                    break;
            }
        } catch (Exception $exc) {
            $aResponse = array(
                'status'  => 0,
                'message' => $exc . trans('validation.custom.error-title'),
            );
        }

        return Response::json($aResponse);
    }

    public function postAjaxRemovePage($page, $id) {

        $aResponse = array(
            'status'  => 200,
            'message' => trans('validation.custom.success-title'),
        );

        try {
            switch ($page) {
                case 'role':
                    $role = Role::find($id);
                    $role->delete();
                    break;

                case 'permission':
                    $permission = Permission::find($id);
                    $permission->delete();
                    break;

                default:
                    break;
            }
        } catch (Exception $exc) {
            $aResponse = array(
                'status'  => 0,
                'message' => trans('validation.custom.error-title'),
            );
        }

        return Response::json($aResponse);
    }

}
